#!/usr/bin/env python
import sys
import class_set
import helper
from sets import Set

class FollowListReducer(helper.ReducerHelper):
    def loader(self, line):
        line = line.strip()
        left = line.split('\t')[0]
        right = class_set.UserNode()
        right.init(line.split('\t')[1])
        return (left, right)

    def processor(self, key, lst):
        """
        Parsing the set of operators of this_node
        You should note that there are only "addattention" operator and "delstars" operator
        Because "delfans" operator was inverted as "delstars" at map_reduce #0

        The first loop of this_set only cares about "addattention" operator, and 
        the second loop only cares about "delstars" operator. Note that when you implement "delstars" operator,
        you should take care the timeline of which is happend last.

        Argument:
            this_set, Set of nodes
        Return:
            follow_output, dict of results
        """
        follow_output = {}
        filter_output = {}
        for node in lst:
            if node.getType() == "addattention":
                if node.getId() in follow_output:
                    if node.getTime() > follow_output[node.getId()].getId():
                        follow_output[node.getId()] = node
                    else: # node's update time before the one already in follow_output
                        pass
                else: # node is not in follow_output
                    follow_output[node.getId()] = node
            else: # node's type is not "addattention"
                pass
        for node in lst:
            if node.getType() == "delstars":
                if node.getId() in follow_output:
                    if node.getTime() > follow_output[node.getId()]:
                        del follow_output[node.getId()]
                        filter_output[node.getId()] = node
                    else: # node's update time before the one already in follow_output
                        pass
                else: # node is not in follow_output, maybe it's a mistake
                    filter_output[node.getId()] = node
            else: # node's type is not "delstars"
                pass

        for e in follow_output.values():
            self.allocator(key, e)
        for e in filter_output.values():
            self.allocator(key, e)

def main():
    fr = FollowListReducer()
    fr.reducer()

if __name__ == '__main__':
    main()

